package com.yuexunit.finance.bulkstock.action.v1;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.yuexunit.finance.bulkstock.action.v1.dto.BulkstockCastor;
import com.yuexunit.finance.bulkstock.action.v1.dto.BulkstockWarningCastor;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockCollection;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockCollectionDetail;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockCollectionMaterial;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockGather;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockGatherDetail;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockLatestCollection;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockLatestGather;
import com.yuexunit.finance.bulkstock.action.v1.model.BulkstockWarningLineInfo;
import com.yuexunit.finance.bulkstock.entity.BulkstockCollectionEntity;
import com.yuexunit.finance.bulkstock.entity.BulkstockCollectionMaterialEntity;
import com.yuexunit.finance.bulkstock.entity.BulkstockGatherEntity;
import com.yuexunit.finance.bulkstock.entity.BulkstockLatestCollectionEntity;
import com.yuexunit.finance.bulkstock.entity.BulkstockLatestGatherEntity;
import com.yuexunit.finance.bulkstock.entity.BulkstockWarningEntity;
import com.yuexunit.finance.bulkstock.entity.lexicon.BulkstockGatherAuditStateEnum;
import com.yuexunit.finance.bulkstock.service.BulkstockCollectionMaterialService;
import com.yuexunit.finance.bulkstock.service.BulkstockCollectionService;
import com.yuexunit.finance.bulkstock.service.BulkstockGatherService;
import com.yuexunit.finance.bulkstock.service.BulkstockLatestCollectionService;
import com.yuexunit.finance.bulkstock.service.BulkstockLatestGatherService;
import com.yuexunit.finance.bulkstock.service.BulkstockWarningService;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.WarningSchemeEntity;
import com.yuexunit.finance.project.entity.WarningSchemeResultEntity;
import com.yuexunit.finance.project.entity.lexicon.RelationTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.SettlementStateEnum;
import com.yuexunit.finance.project.entity.lexicon.WarningFactorEnum;
import com.yuexunit.finance.project.entity.lexicon.WarningLevelEnum;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceBulkstockService;
import com.yuexunit.finance.project.service.WarningSchemeResultService;
import com.yuexunit.finance.project.service.WarningSchemeService;
import com.yuexunit.finance.system.entity.DataSourceEntity;
import com.yuexunit.finance.system.service.DataSourceService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;

/**
 * Created by HuangYH on 2015/10/12.
 */
@Implements(BulkstockCollectionActionApi.class)
public class BulkstockCollectionActionApiImpl implements BulkstockCollectionActionApi {

	private BulkstockCollectionService bulkstockCollectionService = ComponentFactory.loadClass(BulkstockCollectionService.class);

	private BulkstockCollectionMaterialService bulkstockCollectionMaterialService = ComponentFactory.loadClass(BulkstockCollectionMaterialService.class);

	private BulkstockGatherService bulkstockGatherService = ComponentFactory.loadClass(BulkstockGatherService.class);

	private BulkstockLatestGatherService bulkstockLatestgatherService = ComponentFactory.loadClass(BulkstockLatestGatherService.class);

	private BulkstockLatestCollectionService bulkstockLatestCollectionService = ComponentFactory.loadClass(BulkstockLatestCollectionService.class);

	private BulkstockWarningService bulkstockwarningService = ComponentFactory.loadClass(BulkstockWarningService.class);
	
	private DataSourceService dataSourceService = ComponentFactory.loadClass(DataSourceService.class);
	
	private WarningSchemeService warningSchemeService = ComponentFactory.loadClass(WarningSchemeService.class);
	
	private FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
	
	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
	
	private FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
	
	private WarningSchemeResultService warningSchemeResultService = ComponentFactory.loadClass(WarningSchemeResultService.class);
	
	private ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
	
	@Transactional
	@Override
	public String createCollectionMaterial(String fileUuid, Long dataSourceId) {
		List<WarningSchemeEntity> wses = warningSchemeService.inquireWarningSchemeList(WarningFactorEnum.BULKSTOCK);
		
		DataSourceEntity dataSource = dataSourceService.inquireDataSource(dataSourceId);
		BulkstockCollectionEntity entity = new BulkstockCollectionEntity();
		entity.setCollector(FinanceSessionContext.getAccountFullName());
		entity.setCollectorId(FinanceSessionContext.getAccountId());
		entity.setRegion(FinanceSessionContext.getRegion());
		List<BulkstockCollectionEntity> entities = BulkstockCastor.fromCollectionMaterial(fileUuid, entity);
		for (BulkstockCollectionEntity e : entities) {
			e.setDataSourceId(dataSource.getDataSourceId());
			e.setDataSource(dataSource.getDataSource());
			bulkstockCollectionService.createBulkstockCollection(e);
		}
		BulkstockCollectionMaterialEntity materialEntity = new BulkstockCollectionMaterialEntity();
		materialEntity.setCollectionDate(DateUtil.todayInt());
		materialEntity.setCollector(FinanceSessionContext.getAccountFullName());
		materialEntity.setCollectorId(FinanceSessionContext.getAccountId());
		materialEntity.setFileUuid(fileUuid);
		materialEntity.setRegion(FinanceSessionContext.getRegion());
		bulkstockCollectionMaterialService.createCollectionMaterial(materialEntity);
		
		bulkstockCollectionMaterialService.callProcedure();
		
		for (BulkstockCollectionEntity e : entities) {
			for (WarningSchemeEntity wse : wses) {
				if (wse == null) {
					continue;
				}
				BigDecimal standard = wse.getStandard();
				BigDecimal warning = wse.getWarning();
				RelationTypeEnum relationType = wse.getRelationType();
				
//				containerInventoryService.inquireUnSupervisionInventoryList(financeId)
				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireProcessingFinanceBulkstockList(e.getBulkstockInfoId());
				
				
				for (FinanceBulkstockEntity fbe : fbes) {
					WarningSchemeResultEntity wsre = null;
					FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(fbe.getFinanceId());
					if (finance == null) {
						continue;
					}
					EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(finance.getEnterpriseId());
					
					wsre = new WarningSchemeResultEntity();
					wsre.setBulkstockId(fbe.getBulkstockId());
					wsre.setBulkstockInfoId(fbe.getBulkstockInfoId());
					wsre.setBulkstockName(fbe.getBulkstockName());
					wsre.setCreateDateTime(DateUtil.now());
					wsre.setEnterpriseId(enterprise.getEnterpriseId());
					wsre.setEnterpriseName(enterprise.getEnterpriseName());
					wsre.setEvaluatePrice(fbe.getEvaluatePrice());
					wsre.setFactor(WarningFactorEnum.BULKSTOCK);
					wsre.setFinanceId(fbe.getFinanceId());
					wsre.setFinanceNumber(finance.getFinanceNumber());
					wsre.setLatestPrice(e.getPrice());
					wsre.setOperator(FinanceSessionContext.getAccountFullName());
					wsre.setOperatorTime(DateUtil.now());
					wsre.setSchemeId(wse.getSchemeId());
					wsre.setSchemeName(wse.getSchemeName());
					wsre.setSettlementState(SettlementStateEnum.UNKNOWN);
					wsre.setWarningLevel(WarningLevelEnum.RED);
					
					if (relationType == RelationTypeEnum.EQ) { //等于
						if (fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(standard)) == 0) {
							wsre.setWarningLevel(WarningLevelEnum.RED);
						} else if (fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(warning)) == 0) {
							wsre.setWarningLevel(WarningLevelEnum.YELLOW);
						} else {
							continue;
						}
					} else if (relationType == RelationTypeEnum.GT) { //大于
						if (fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(standard)) > 0) {
							wsre.setWarningLevel(WarningLevelEnum.RED);
						} else if (fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(warning)) == 0 && fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(standard)) <= 0) {
							wsre.setWarningLevel(WarningLevelEnum.YELLOW);
						} else {
							continue;
						}
					} else if (relationType == RelationTypeEnum.LT) { //小于
						if (fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(standard)) < 0 && fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(warning)) >= 0) {
							wsre.setWarningLevel(WarningLevelEnum.RED);
						} else if (fbe.getEvaluatePrice().compareTo(e.getPrice().multiply(warning)) < 0) {
							wsre.setWarningLevel(WarningLevelEnum.YELLOW);
						} else {
							continue;
						}
					}
					warningSchemeResultService.createWarningSchemeResult(wsre);
				}
			}
			
		}
		
		
		return null;
	}

	@Transactional
	@Override
	public void disableCollectionMaterial(Long bulkstockCollectionMaterialId) {
		bulkstockCollectionMaterialService.disableCollectionMaterial(bulkstockCollectionMaterialId);
	}

	@Override
	public PageList<BulkstockCollectionMaterial> inquireCollectionMaterialPageList(String startDate, String endDate, String region, String collector, PageCriteria page) {
		Integer iStartDate = DateUtils.parseDateInt(startDate);
		Integer iEndDate = DateUtils.parseDateInt(endDate);
		PageList<BulkstockCollectionMaterialEntity> pageList = bulkstockCollectionMaterialService.inquireCollectionMaterialList(iStartDate, iEndDate, region, collector, page);
		PageList<BulkstockCollectionMaterial> results = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockCollectionMaterialEntity entity : pageList) {
			results.add(BulkstockCastor.toBulkstockCollectionMaterial(entity));
		}
		return results;
	}

	// ================================================================================================================//
	@Transactional
	@Override
	public String createBulkstockCollection(BulkstockCollection bulkstockCollection) {
		BulkstockCollectionEntity entity = BulkstockCastor.fromBulkstockCollection(bulkstockCollection);
		entity.setCollector(FinanceSessionContext.getAccountFullName());
		entity.setCollectorId(FinanceSessionContext.getAccountId());
		entity.setRegion(FinanceSessionContext.getRegion());
		bulkstockCollectionService.createBulkstockCollection(entity);
		return String.valueOf(entity.getCollectionId());
	}

	@Transactional
	@Override
	public void updateBulkstockCollection(BulkstockCollectionDetail bulkstockCollectionDetail) {
		BulkstockCollectionEntity entity = BulkstockCastor.fromBulkstockCollection(bulkstockCollectionDetail);
		entity.setCollector(FinanceSessionContext.getAccountFullName());
		entity.setCollectorId(FinanceSessionContext.getAccountId());
		entity.setRegion(FinanceSessionContext.getRegion());
		bulkstockCollectionService.updateBulkstockCollection(entity);
	}

	@Transactional
	@Override
	public void disableBulkstockCollection(Long collectionId) {
		bulkstockCollectionService.disableBulkstockCollection(collectionId);
	}

	@Override
	public BulkstockCollectionDetail inquireBulkstockCollectionDetail(Long collectionId) {
		BulkstockCollectionEntity entity = bulkstockCollectionService.inquireBulkstockCollectionDetail(collectionId);
		BulkstockCollectionDetail detail = BulkstockCastor.toBulkstockCollectionDetail(entity);
		return detail;
	}

	@Override
	public PageList<BulkstockCollection> inquireBulkstockCollectionPageList(Long categoryId, String startDate, String endDate, String bulkstockName, String bulkstockType, String specification, String manufacturer, String region,
			PageCriteria page) {
		Integer dateBegin = DateUtils.parseDateInt(startDate);
		Integer dateEnd = DateUtils.parseDateInt(endDate);
		PageList<BulkstockCollectionEntity> entityList = bulkstockCollectionService.inquireBulkstockCollectionPageList(categoryId, dateBegin, dateEnd, bulkstockName, bulkstockType, specification, manufacturer, region, page);
		PageList<BulkstockCollection> bulkstockCollectionList = new PageList<BulkstockCollection>(page, entityList.getTotalRecordCount());
		for (BulkstockCollectionEntity entity : entityList) {
			bulkstockCollectionList.add(BulkstockCastor.toBulkstockCollectionDetail(entity));
		}
		return bulkstockCollectionList;
	}

	@Override
	public PageList<BulkstockLatestCollection> inquireBulkstockLatestCollectionList(Long bulkstockCategoryId, Long bulkstockInfoId, String bulkstockName, String specification, String region, Long dataSourceId, PageCriteria page) {
		PageList<BulkstockLatestCollectionEntity> pageList = bulkstockLatestCollectionService.inquireBulkstockLatestCollectionPageList(bulkstockCategoryId, bulkstockInfoId, bulkstockName, specification, region, null, page);
		PageList<BulkstockLatestCollection> resultList = new PageList<BulkstockLatestCollection>(page, pageList.getTotalRecordCount());
		for (BulkstockLatestCollectionEntity entity : pageList) {
			resultList.add(BulkstockCastor.toBulkstockLatestCollection(entity));
		}
		return resultList;
	}
	// ===============================================================================================================================================================//
	@Transactional
	@Override
	public void importBulkstockGather(String fileUuid) {
		List<BulkstockGatherEntity> entities = BulkstockCastor.fromBulkstockGatherMaterial(fileUuid);
		
		for (BulkstockGatherEntity e : entities) {
			bulkstockGatherService.createBulkstockGather(e);
			
		}
	}

	@Transactional
	@Override
	public String createBulkstockGather(BulkstockGather bulkstockGather) {
		BulkstockGatherEntity entity = BulkstockCastor.fromBulkstockGather(bulkstockGather);
		return String.valueOf(bulkstockGatherService.createBulkstockGather(entity));
	}

	@Override
	public void updateBulkstockGather(BulkstockGatherDetail detail) {
		BulkstockGatherEntity entity = BulkstockCastor.fromBulkstockGather(detail);
		entity.setGatherId(detail.getGatherId());
		bulkstockGatherService.updateBulkstockGather(entity);
	}

	@Transactional
	@Override
	public void disableBulkstockGather(Long gatherId) {
		bulkstockGatherService.disableBulkstockGather(gatherId);
	}

	@Transactional
	@Override
	public void issueBulkstockGather(Long gatherId) {
		BulkstockGatherEntity entity = bulkstockGatherService.inquireBulkstockGatherDetail(gatherId);
		entity.setAuditor(FinanceSessionContext.getAccountFullName());
		entity.setAuditorId(FinanceSessionContext.getAccountId());
		entity.setAuditState(BulkstockGatherAuditStateEnum.APPROVED);
		entity.setIssueDateTime(new Date());
		bulkstockGatherService.updateBulkstockGather(entity);
	}

	@Override
	public BulkstockGatherDetail inquireBulkstockGatherDetail(Long gatherId) {
		BulkstockGatherEntity entity = bulkstockGatherService.inquireBulkstockGatherDetail(gatherId);
		return BulkstockCastor.toBulkstockGatherDetail(entity);
	}

	@Override
	public PageList<BulkstockGatherDetail> inquireBulkstockGatherList(Long categoryId, Long bulkstockInfoId, String bulkstockName, String specification, String startTime, String endTime, String startPriceDate, String endPriceDate,
			Integer auditState, PageCriteria page) {
		Integer iStartTime = DateUtils.parseDateInt(startTime);
		Integer iEndTime = DateUtils.parseDateInt(endTime);
		PageList<BulkstockGatherEntity> entities = bulkstockGatherService.inquireBulkstockGatherPageList(categoryId, bulkstockInfoId, bulkstockName, specification, iStartTime, iEndTime, startPriceDate, endPriceDate, auditState, page);
		PageList<BulkstockGatherDetail> results = new PageList<>(page, entities.getTotalRecordCount());
		for (BulkstockGatherEntity entity : entities) {
			results.add(BulkstockCastor.toBulkstockGatherDetail(entity));
		}
		return results;
	}

	@Override
	public PageList<BulkstockLatestGather> inquireBulkstockGatherLatestList(Long bulkstockCategoryId, Long bulkstockInfoId, String bulkstockName, String specification, PageCriteria page) {
		PageList<BulkstockLatestGatherEntity> pageList = bulkstockLatestgatherService.inquireBulkstockLatestgatherPageList(bulkstockCategoryId, bulkstockInfoId, bulkstockName, specification, page);
		PageList<BulkstockLatestGather> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockLatestGatherEntity entity : pageList) {
			resultList.add(BulkstockCastor.toBulkstockLatestGather(entity));
		}
		return resultList;
	}

	@Override
	public BulkstockLatestGather inquireBulkstockLatestGather(Long bulkstockInfoId) {
		BulkstockLatestGatherEntity entity = bulkstockLatestgatherService.inquireBulkstockLatestgather(bulkstockInfoId);
		return BulkstockCastor.toBulkstockLatestGather(entity);
	}

	// ===============================================================================================================================================================//
	
	@Override
	public PageList<BulkstockWarningLineInfo> inquireBulkstockWarningPageList(PageCriteria page) {
		PageList<BulkstockWarningEntity> pageList = bulkstockwarningService.inquirebulkstockWarningPageList(page);
		PageList<BulkstockWarningLineInfo> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (BulkstockWarningEntity entity : pageList) {
			resultList.add(BulkstockWarningCastor.toBulkstockWarningInfo(entity));
		}
		return resultList;
	}
}